package com.cneport.das.server.util.wmq;

import com.cneport.das.server.conf.ConfigCaches;
import com.cneport.das.server.trans.conf.Authen;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.Map;
import java.util.Set;

/**
 * @Desc 启动时初始化MQ的队列
 * @Ver 1.0
 * @Author GavinZhang
 * @Company 东方物通科技有限（北京）公司
 * @Date 2021-12-23 14:21:03
 */
@Component
@Slf4j
@ConditionalOnProperty(name = "mq.wmq.enable", havingValue = "true")
public class QueueInitializer {
    @Autowired
    private WebSphereMQHelper webSphereMQHelper;
    @Autowired
    private ConfigCaches configCaches;

    @PostConstruct
    public void init() {
        log.info("尝试初始化队列！");
        Set<String> existQ = webSphereMQHelper.listQueueNames();

        Map<String, Authen> allCorpAuth = configCaches.getAllCorpAuth();
        Collection<Authen> values = allCorpAuth.values();
        for (Authen auth : values) {
            String req_q = auth.getRcvQueue();
            String rcv_q = auth.getReqQueue();
            String corpName = auth.getCorpName();
            if (!existQ.contains(req_q)) {
                boolean queue = webSphereMQHelper.createQueue(req_q, corpName);
                if (queue) {
                    log.info("创建了 " + corpName + " 的Queue:" + req_q);
                } else {
                    log.error("创建 " + corpName + " 的Queue:" + req_q + "失败！");
                }
            }
            if (!existQ.contains(rcv_q)) {
                boolean queue = webSphereMQHelper.createQueue(rcv_q, corpName);
                if (queue) {
                    log.info("创建了 " + corpName + " 的Queue:" + rcv_q);
                } else {
                    log.error("创建 " + corpName + " 的Queue:" + rcv_q + "失败！");
                }

            }
        }
        log.info("队列初始化完成！");

    }
}
